home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / misc / upnp-tester.py
Text File  |  2009-05-12  |  7KB  |  210 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # Licensed under the MIT license
  5. # http://opensource.org/licenses/mit-license.php
  6.  
  7. # Copyright 2008, Frank Scholz <coherence@beebits.net>
  8.  
  9. # upnp-tester.py
  10. #
  11. # very basic atm
  12. #
  13. # provides these functions:
  14. #
  15. # list           - display all devices
  16. # extract <uuid> - extract device and service xml files and put them in a
  17. #                  /tmp/<uuid> directory
  18. # send <uuid>    - pack the before extracted xml files in a tar.gz and
  19. #                  send them via email to the Coherence googlemail account
  20. #
  21.  
  22. import os
  23. from sets import Set
  24.  
  25. from twisted.internet import stdio
  26. from twisted.protocols import basic
  27. from twisted.internet import protocol
  28.  
  29. try:
  30.     from twisted.mail import smtp
  31.  
  32.     from twisted.names import client as namesclient
  33.     from twisted.names import dns
  34.  
  35.     import StringIO
  36.  
  37.     class SMTPClient(smtp.ESMTPClient):
  38.  
  39.         """ build an email message and send it to our googlemail account
  40.         """
  41.  
  42.         def __init__(self, mail_from, mail_to, mail_subject, mail_file, *args, **kwargs):
  43.             smtp.ESMTPClient.__init__(self, *args, **kwargs)
  44.             self.mailFrom = mail_from
  45.             self.mailTo = mail_to
  46.             self.mailSubject = mail_subject
  47.             self.mail_file =  mail_file
  48.             self.mail_from =  mail_from
  49.  
  50.         def getMailFrom(self):
  51.             result = self.mailFrom
  52.             self.mailFrom = None
  53.             return result
  54.  
  55.         def getMailTo(self):
  56.             return [self.mailTo]
  57.  
  58.         def getMailData(self):
  59.             from email.mime.application import MIMEApplication
  60.             from email.mime.multipart import MIMEMultipart
  61.  
  62.             msg = MIMEMultipart()
  63.             msg['Subject'] = self.mailSubject
  64.             msg['From'] = self.mail_from
  65.             msg['To'] = self.mailTo
  66.             fp = open(self.mail_file, 'rb')
  67.             tar = MIMEApplication(fp.read(),'x-tar')
  68.             fp.close()
  69.             tar.add_header('Content-Disposition', 'attachment', filename=os.path.basename(self.mail_file))
  70.             msg.attach(tar)
  71.             return StringIO.StringIO(msg.as_string())
  72.  
  73.         def sentMail(self, code, resp, numOk, addresses, log):
  74.             print 'Sent', numOk, 'messages'
  75.  
  76.     class SMTPClientFactory(protocol.ClientFactory):
  77.         protocol = SMTPClient
  78.  
  79.         def __init__(self, mail_from, mail_to, mail_subject, mail_file, *args, **kwargs):
  80.             self.mail_from = mail_from
  81.             self.mail_to = mail_to
  82.             self.mail_subject = mail_subject
  83.             self.mail_file = mail_file
  84.  
  85.         def buildProtocol(self, addr):
  86.             return self.protocol(self.mail_from, self.mail_to,
  87.                                  self.mail_subject, self.mail_file,
  88.                                  secret=None, identity='localhost')
  89.  
  90. except ImportError:
  91.     pass
  92.  
  93. from twisted.internet import reactor, defer
  94. from twisted.web import client
  95.  
  96. from coherence.base import Coherence
  97.  
  98. class UI(basic.LineReceiver):
  99.     from os import linesep as delimiter
  100.  
  101.     def connectionMade(self):
  102.         self.print_prompt()
  103.  
  104.     def lineReceived(self, line):
  105.         args = line.strip().split()
  106.         if args:
  107.             cmd = args[0].lower()
  108.             if hasattr(self, 'cmd_%s' % cmd):
  109.                 getattr(self, 'cmd_%s' % (cmd))(args[1:])
  110.             elif cmd == "?":
  111.                 self.cmd_help(args[1:])
  112.             else:
  113.                 self.transport.write("""Unknown command '%s'\n"""%(cmd))
  114.         self.print_prompt()
  115.  
  116.     def cmd_help(self,args):
  117.         "help -- show help"
  118.         methods = Set([ getattr(self, x) for x in dir(self) if x[:4] == "cmd_" ])
  119.         self.transport.write("Commands:\n")
  120.         for method in methods:
  121.             if hasattr(method, '__doc__'):
  122.                 self.transport.write("%s\n"%(method.__doc__))
  123.  
  124.     def cmd_list(self, args):
  125.         "list -- list devices"
  126.         self.transport.write("Devices:\n")
  127.         for d in self.coherence.get_devices():
  128.             self.transport.write(str("%s %s [%s/%s/%s]\n" % (d.friendly_name, ':'.join(d.device_type.split(':')[3:5]), d.st, d.usn.split(':')[1], d.host)))
  129.  
  130.     def cmd_extract(self, args):
  131.         "extract <uuid> -- download xml files from device"
  132.         device = self.coherence.get_device_with_id(args[0])
  133.         if device == None:
  134.             self.transport.write("device %s not found - aborting\n" % args[0])
  135.         else:
  136.             self.transport.write(str("extracting from %s @ %s\n" % (device.friendly_name, device.host)))
  137.             try:
  138.                 l = []
  139.  
  140.                 def device_extract(workdevice, path):
  141.                     tmp_dir = os.path.join(path,workdevice.get_uuid())
  142.                     os.mkdir(tmp_dir)
  143.                     d = client.downloadPage(workdevice.get_location(),os.path.join(tmp_dir,'device-description.xml'))
  144.                     l.append(d)
  145.  
  146.                     for service in workdevice.services:
  147.                         d = client.downloadPage(service.get_scpd_url(),os.path.join(tmp_dir,'%s-description.xml'%service.service_type.split(':',3)[3]))
  148.                         l.append(d)
  149.  
  150.  
  151.                     for ed in workdevice.devices:
  152.                         device_extract(ed, tmp_dir)
  153.  
  154.                 def finished(result):
  155.                     self.transport.write(str("\nextraction of device %s finished\nfiles have been saved to /tmp/%s\n" %(args[0],args[0])))
  156.                     self.print_prompt()
  157.  
  158.                 device_extract(device,'/tmp')
  159.  
  160.                 dl = defer.DeferredList(l)
  161.                 dl.addCallback(finished)
  162.             except Exception, msg:
  163.                 self.transport.write(str("problem creating download directory %s\n" % msg))
  164.  
  165.     def cmd_send(self, args):
  166.         "send <uuid> -- send before extracted xml files to the Coherence home base"
  167.         if os.path.isdir(os.path.join('/tmp',args[0])) == 1:
  168.             cwd = os.getcwd()
  169.             os.chdir('/tmp')
  170.             import tarfile
  171.             tar = tarfile.open(os.path.join('/tmp',args[0]+'.tgz'), "w:gz")
  172.             for file in os.listdir(os.path.join('/tmp',args[0])):
  173.                 tar.add(os.path.join(args[0],file))
  174.             tar.close()
  175.             os.chdir(cwd)
  176.  
  177.             def got_mx(result):
  178.                 mx_list = result[0]
  179.                 mx_list.sort(lambda x, y: cmp(x.payload.preference, y.payload.preference))
  180.                 if len(mx_list) > 0:
  181.                     import posix, pwd
  182.                     import socket
  183.                     reactor.connectTCP(str(mx_list[0].payload.name), 25,
  184.                         SMTPClientFactory('@'.join((pwd.getpwuid(posix.getuid())[0],socket.gethostname())), 'upnp.fingerprint@googlemail.com', 'xml-files', os.path.join('/tmp',args[0]+'.tgz')))
  185.  
  186.             mx = namesclient.lookupMailExchange('googlemail.com')
  187.             mx.addCallback(got_mx)
  188.  
  189.  
  190.     def cmd_quit(self, args):
  191.         "quit -- quits this program"
  192.         reactor.stop()
  193.  
  194.     cmd_exit = cmd_quit
  195.  
  196.     def print_prompt(self):
  197.         self.transport.write('>>> ')
  198.  
  199.  
  200.  
  201. if __name__ == '__main__':
  202.  
  203.     c = Coherence({'logmode':'none'})
  204.     ui = UI()
  205.     ui.coherence = c
  206.  
  207.     stdio.StandardIO(ui)
  208.  
  209.     reactor.run()
  210.